package dept_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
	"net/http"
)

// GetChildrenDepart 获取子部门
func GetChildrenDepart(parentId int64, allDepart []*AllDepart) []*DepartList {
	data := make([]*DepartList, 0)
	for _, v := range allDepart {
		if parentId == v.ParentId {
			data = append(data, &DepartList{
				ID:        v.ID,
				Name:      v.Name,
				Order:     v.Order,
				ParentId:  v.ParentId,
				SubDepart: GetChildrenDepart(v.ID, allDepart),
			})
		}
	}
	return data
}

// GetAllDepart 生成部门树
func GetAllDepart(allDepart []*AllDepart) []*DepartList {
	reply := make([]*DepartList, 0)
	for _, v := range allDepart {
		if v.ParentId == 0 {
			reply = append(reply, &DepartList{
				ID:        v.ID,
				Name:      v.Name,
				Order:     v.Order,
				ParentId:  v.ParentId,
				SubDepart: GetChildrenDepart(v.ID, allDepart),
			})
		}
	}
	return reply
}

// Departs 部门处理逻辑
func Departs(c *gin.Context) {
	data := make([]*DepartList, 0)
	allDepart := make([]*AllDepart, 0)
	tx := database.DB.Model(new(models.Department)).Select("id, `name`, parent_id,`order`").Where("deleted_flag != 1").Order("`order` ASC")
	err := tx.Find(&allDepart).Error

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	data = GetAllDepart(allDepart)
	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"msg":    "操作成功",
		"result": data,
	})

}

// GetDepartList 获取用户列表
func GetDepartList(c *gin.Context) {
	Departs(c)
}
